<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="text" bf-model="name">
  <input type="text" bf-model="name">
  <input type="text">
  <input type="text" bf-model="age">


  <script>
    var data = {
      name: '张三',
      age: 18
    }
    var dep = {
      subs: {
        // name:[c1],
        // age:[]
      },
      add(type, fn) {
        if (!this.subs[type]) {
          this.subs[type] = []
        }
        this.subs[type].push(fn)
      },
      notify(type) {
        var events = this.subs[type]
        for (var i = 0; i < events.length; i++) {
          events[i]()
        }
      }
    }

    for (var key in data) {
      let _value = data[key]
      let _key = key
      Object.defineProperty(data, key, {
        get() {
          return  _value
        },
        set(val) {
          _value = val
          dep.notify(_key)
        }
      })
    }
    var inputs = document.querySelectorAll('input')
    // 初始化数据
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i]
      // 判断是有有 bf-model 属性
      if (input.hasAttribute('bf-model')) {
        // modelkey ==  name/age
        var modelKey = input.getAttribute('bf-model')
        // 赋值
        input.value = data[modelKey]
        // 事件 input
        input.oninput = (function (modelKey) {
          return function () {
            data[modelKey] = this.value
          }
        })(modelKey);

        // 让数据和 Dom 关联
        dep.add(modelKey, (function (input, modelKey) {
          return function () {
            input.value = data[modelKey]
          }
        })(input, modelKey))
      }
    }
  </script>
</body>

</html>